package com.xuef.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.xuef.util.FileUploadHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created by moveb on 2018/5/21.
 */
@Service
public class QiniuServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(QiniuServiceImpl.class);

    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "P15eSG5gJA0k0k2f7LYYjfYSPWbDJIyn3mWOFjee"; //这两个登录七牛 账号里面可以找到
    String SECRET_KEY = "HBNthyIaGAPMGn7Of6QuE7l63yh9F8k73zduBZNY";

    //要上传的空间
    String bucketname = "blog-avatar"; //填写新建的那个存储空间对象的名称

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    UploadManager uploadManager = new UploadManager(cfg);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(){
        return auth.uploadToken(bucketname);
    }
    //普通上传
    public String upload(MultipartFile file) throws IOException {
        String key = new StringBuilder().append(FileUploadHelper.randomFilename())
                .append(".").append(FileUploadHelper.suffixOfFile(file.getOriginalFilename())).toString();
        logger.info("上传文件名： " + key);
        try {
            //调用put方法上传
            Response res = uploadManager.put(file.getBytes(), key, getUpToken());

            //System.out.println(res.isOK());

            System.out.println(res.bodyString());
        } catch (IOException e) {
            logger.info("upload 异常");
            throw e;
        }
        return FileUploadHelper.avatarUrl(key);
    }
}
